package com.lyn.utils;

import android.app.Activity;
import android.view.View;

import androidx.fragment.app.Fragment;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

/**
 * 注解绑定控件
 */
public class BindViewUtil {

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    public @interface BindView {
        int id() default 0;
    }

    public static void scanning(Activity activity) throws IllegalAccessException {
        if (activity == null) return;
        Class<?> aClass = activity.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            boolean annotationPresent = field.isAnnotationPresent(BindView.class);
            if (annotationPresent) {
                BindView bindView = field.getAnnotation(BindView.class);
                int id = bindView.id();
                View view = activity.findViewById(id);
                field.setAccessible(true);
                field.set(activity, view);
            }
        }
    }

    public static void scanning(Fragment fragment) throws IllegalAccessException {
        if (fragment == null) return;
        Class<?> aClass = fragment.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            boolean annotationPresent = field.isAnnotationPresent(BindView.class);
            if (annotationPresent) {
                BindView bindView = field.getAnnotation(BindView.class);
                int id = bindView.id();
                View view = fragment.getView().findViewById(id);
                field.setAccessible(true);
                field.set(fragment, view);
            }
        }
    }
}
